package IC.lir;

import java.util.HashMap;
import IC.Error.*;
import IC.Error.Error.ErrorType;

public class CodeGenerationImpl 
{
	@SuppressWarnings("unchecked")
	public static Lir GenerateCode(IC.AST.Program root, boolean isOptimize)
	{
		Lir ret = new Lir();
		ret.ClassStructures = (HashMap<String, ClassStructure>)new ClassCreatorVisitor().Visit(root);
		root.RunBottomUpOnTree(new ImmediatesCalcVIsitor());
		if (isOptimize)
		{
			root.Visit(new RegisterWeightCalcVisitor());
			new OptimizedFunctionBodyCreatorVisitor(ret).Visit(root);
		}
		else
			new FunctionBodyCreatorVisitor(ret).Visit(root);
		return ret;
	}
	
	public static boolean PrintLir(Lir lir, String fileName)
	{
		try
		{
			java.io.Writer writer = new java.io.FileWriter(fileName);
			writer.write(lir.toString().replaceAll("\n", "\r\n"));
			writer.close();	
		}
		catch (java.io.IOException e)
		{
			ErrorStack.Push(new ErrorString(ErrorType.CodeGeneration, "Couldn't write output to lir file."));
			return false;
		}
	
		return true;
	}
}
